package com.visualization.server.controller;


import com.visualization.server.entities.User;
import com.visualization.server.service.UserService;
import com.visualization.server.utils.ResultData;
import com.visualization.server.utils.ReturnCodeEnum;
import org.apache.ibatis.annotations.Param;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;


    //添加用户
    @PostMapping("/addUser")
    public ResultData<String> addUser(@RequestBody User user){
        Integer i = userService.addUser(user);
        if (i==1){
            return ResultData.success("添加成功");
        }
        return ResultData.fail(ReturnCodeEnum.RC88.getCode(), ReturnCodeEnum.RC88.getMessage());
    }


    //删除用户
    @PostMapping("/deleteUser")
    public ResultData<String> deleteUser(@RequestBody User user){
        Integer i = userService.deleteUser(user);
        if (i==1){
            return ResultData.success("删除成功");
        }
        return ResultData.fail(ReturnCodeEnum.RC88.getCode(), ReturnCodeEnum.RC88.getMessage());
    }


    //通过用户id删除用户信息
    @GetMapping("/deleteUserById/{id}")
    public ResultData<String> deleteUser(@PathVariable("id")Integer id){
        //先查询User
        User userById = userService.getUserById(id);
        if (userById!=null){
            Integer i = userService.deleteUser(userById);
            if (i==1){
                return ResultData.success("删除成功");
            }
            return ResultData.fail(ReturnCodeEnum.RC88.getCode(), ReturnCodeEnum.RC88.getMessage());
        }
        return ResultData.fail(ReturnCodeEnum.RC88.getCode(),"用户不存在");
    }



    //更新用户信息
    @PostMapping("/updateUser")
    public ResultData<String> updateUser(@RequestBody User user){
        Integer i = userService.updateUser(user);
        if (i==1){
            return ResultData.success("修改成功");
        }
        return ResultData.fail(ReturnCodeEnum.RC88.getCode(), ReturnCodeEnum.RC88.getMessage());
    }

    //通过id查询用户
    @GetMapping("/getUserById/{id}")
    public ResultData<Object> getUserById(@PathVariable("id") Integer id){
        User user = userService.getUserById(id);
        if (user!=null){
            return ResultData.success(user);
        }
        return ResultData.fail(ReturnCodeEnum.RC88.getCode(), "用户不存在");
    }


    //查询所有用户
    @GetMapping("/getUserList")
    public ResultData<List<User>>   getUserList(){
        List<User> userList = userService.getUserList();
        return ResultData.success(userList);
    }





}
